package com.example.backend.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.backend.mapper.UserRoleMapper;
import com.example.backend.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Jcy
 * @Date 2022/5/6
 */

@Component
public class AdminFilter implements HandlerInterceptor {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isLogin = false;
        final String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token))
        {
            Boolean Exist = JWTUtil.verify(token, JWTUtil.getUserid(token));
            if (!Exist) {
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setStatus(417);
                response.getWriter().write("{\n" +
                        "\t\"resultCode\": 417,\n" +
                        "\t\"message\": \"token失效，请重新获取\",\n" +
                        "\t\"data\": null\n" +
                        "}");
                return isLogin;
            }
            if (Exist){
                if(userRoleMapper.getUserRole(Integer.parseInt(JWTUtil.getUserid(token)))==2){
                    response.setContentType("application/json;charset=UTF-8");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(403);
                    response.getWriter().write("{\n" +
                            "\t\"resultCode\": 403,\n" +
                            "\t\"message\": \"请登录管理员账户\",\n" +
                            "\t\"data\": null\n" +
                            "}");
                    return isLogin;
                }
                isLogin = true;
                return isLogin;
            }
            isLogin = true;
            return isLogin;

        }
        if (!isLogin) {
            response.setContentType("application/json;charset=UTF-8");
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setStatus(401);
            response.getWriter().write("{\n" +
                    "\t\"resultCode\": 401,\n" +
                    "\t\"message\": \"未通过登录认证，请在权限申请页面申请权限\",\n" +
                    "\t\"data\": null\n" +
                    "}");
        }
        return isLogin;
    }

}
